package com.auerdi.ui.fragment.e_my.orders.childs.comment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auerdi.R;
import com.auerdi.dialog.SearchGoodsDialog;
import com.auerdi.ui.fragment.c_officer.child.event.RefreshBiscoverEvent;
import com.auerdi.utils.Tool;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.ResultResponce;
import com.example.egghttp.retrofit.beans.goods.Product;
import com.squareup.picasso.Picasso;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import es.dmoral.toasty.Toasty;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by tse on 16/6/30.
 */
public class ADCommentPostFragment extends SwipeBackFragment {

    Unbinder unbinder;
    @BindView(R.id.recy)
    RecyclerView recyPhoto;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.title_left)
    RelativeLayout titleLeft;
    @BindView(R.id.add_pro)
    TextView addPro;
    @BindView(R.id.toprecy)
    RecyclerView toprecy;
    private static final int SELECT_PHOTO = 112;
    private static final int CODEBIG = 113;
    @BindView(R.id.post_off)
    LinearLayout postOff;
    @BindView(R.id.editTitle)
    EditText editTitle;
    @BindView(R.id.editContent)
    EditText editContent;
    private List<ImagHelp> mBottomOffercerList = new ArrayList<>();
    private List<Product> myCenterGoodsList = new ArrayList<>();
    private File outputImage;
    public static Uri uriPho;

    public static ADCommentPostFragment newInstance() {

        Bundle args = new Bundle();
        ADCommentPostFragment fragment = new ADCommentPostFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBottomOffercerList.add(new ImagHelp());
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            builder.detectFileUriExposure();
        }

        L.d("hcia", "onCreate:");
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (getActivity().checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }

        File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "eggs");
        if (!folder.exists()) {// 如果資料夾不存在，創建一個
            folder.mkdirs(); //這裡要用.mkdirs()方法，父類資料夾不存在時，可以自動創建
        }


    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.comment_pos, container, false);

        L.d("hcia", "onCreateView:");
        unbinder = ButterKnife.bind(this, view);

        postOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                JSONArray jsonArray = new JSONArray();
                String id_list = "";

                for (int i = 0; i < myCenterGoodsList.size(); i++) {

                    if (i == 0) {
                        String cage = myCenterGoodsList.get(i).getHuodongType() + "_" + myCenterGoodsList.get(i).getId();


                        id_list = cage + "";
                    } else {
                        String cage = myCenterGoodsList.get(i).getHuodongType() + "_" + myCenterGoodsList.get(i).getId();
                        id_list = id_list + "," + cage;


                    }
                }

                L.d("hcia", "id_list:" + id_list);
                for (ImagHelp ww : mBottomOffercerList) {

                    if (ww.getUri() != null) {
                        String tmpStr = null;
                        try {
                            tmpStr = Tool.bitmapToBase64(Tool.getBitmapFormUri(getActivity(), ww.getUri()));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        jsonArray.put("data:image/png;base64," + tmpStr);
                    }

                }


                Map<String, Object> ww = new HashMap<>();
                ww.put("title", editTitle.getText());
                ww.put("meg", editContent.getText());
                ww.put("id_list", id_list);
                ww.put("strsss", jsonArray);

                L.d("hcia", " ww.get(id_list):" + ww.get(id_list));
//                L.d("hcia", "ww:" + ww);
                RetrofitClient.getPDAClient().create(AdService.class).updateProfile(ww)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BOb<ResultResponce>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(BOb<ResultResponce> resultResponceBOb) {
                                if (resultResponceBOb.getCode().equals("10000")) {


                                    EventBus.getDefault().post(new RefreshBiscoverEvent());

                                    Toasty.success(getActivity(), "上传成功").show();
                                    pop();
                                }

                            }
                        });

            }
        });

        toprecy.setLayoutManager(new GridLayoutManager(getContext(), 1));
        toprecy.setAdapter(new CommonAdapter<Product>(getActivity(), R.layout.item_searchpr_cut, myCenterGoodsList) {
            @Override
            protected void convert(ViewHolder viewHolder, final Product item, int position) {
                ImageView gPic = viewHolder.getView(R.id.img);
                viewHolder.setText(R.id.title, "" + item.getTitle());
                viewHolder.setText(R.id.subtitle, "" + item.getShareTitle());
                Picasso.get().load(item.getLunboImg()).error(R.mipmap.logo).placeholder(R.mipmap.logo).fit().into(gPic);//

                viewHolder.getView(R.id.cut).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myCenterGoodsList.remove(item);
                        notifyDataSetChanged();
                    }
                });

            }
        });


        recyPhoto.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyPhoto.setAdapter(new CommonAdapter<ImagHelp>(getContext(), R.layout.item_officer_pos, mBottomOffercerList) {
            @Override
            protected void convert(ViewHolder viewHolder, final ImagHelp imagHelp, int position) {


                ImageView img = viewHolder.getView(R.id.img);

                L.d("hcia", position + ":item.getUri():" + imagHelp.getUri());

                if (imagHelp.getUri() == null) {
                    img.setImageResource(imagHelp.getSrc());
                    viewHolder.setVisible(R.id.ccut, false);
                    viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showUploadPic();
                        }
                    });

                } else {
                    img.setImageURI(imagHelp.getUri());
                    viewHolder.getView(R.id.ccut).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mBottomOffercerList.remove(imagHelp);
                            notifyDataSetChanged();
                        }
                    });
                }
            }
        });

        addPro.setOnClickListener(v -> SearchGoodsDialog.newInstance(num -> {
            myCenterGoodsList.add(num);
            toprecy.getAdapter().notifyDataSetChanged();
        }).show(getFragmentManager(), ""));

        View tpview = attachToSwipeBack(view);

        return tpview;
    }

    private Handler myHandler = new Handler();


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        L.d("hcia", "requestCode:" + requestCode);
        if (resultCode == RESULT_OK) {

            if (requestCode == CODEBIG) {//照片


                try {

                    L.d("hcia", "data:" + data);

                    L.d("hcia", "uriPho:" + uriPho);

                    myHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            L.d("hcia", "uriPho:" + uriPho);
                            ImagHelp tmp = new ImagHelp(uriPho);
                            mBottomOffercerList.add(tmp);

                            if (recyPhoto != null)
                                recyPhoto.getAdapter().notifyDataSetChanged();

                        }
                    }, 0);

                } catch (Exception e) {
                    L.d("hcia", "e:" + e);
                    e.printStackTrace();
                }


            }

            if (requestCode == SELECT_PHOTO) {//相簿


                try {

                    myHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Uri uri = data.getData();
                            L.d("hcia", "uri:" + uri);


                            L.d("hcia", "uri:" + uri);
                            ImagHelp tmp = new ImagHelp(uri);
                            mBottomOffercerList.add(tmp);
                            recyPhoto.getAdapter().notifyDataSetChanged();
                        }
                    }, 1000);

//                    final File file = new File(selectedFilePath);
//                    uplaoPic(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        L.d("hcia", "onDestroyView:");
        unbinder.unbind();
    }


    private void showUploadPic() {
        AlertView ee = new AlertView.Builder().setContext(getActivity())

                .setStyle(AlertView.Style.ActionSheet)
                .setTitle("上传")
                .setDestructive(new String[]{"拍照", "从相册中选择"})
                .setMessage(null)
                .setCancelText("取消")
                .setOthers(null)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        L.d("hcia", "position:" + position);

                        if (position == 0) {
//
                            try {
                                File EggForder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "eggs".toString());
                                outputImage = File.createTempFile(
                                        "eggimage",  /* prefix */
                                        ".jpg",         /* suffix */
                                        EggForder      /* directory */
                                );
                                L.d("hcia", "outputImage:" + outputImage);
                                if (outputImage.exists()) {
                                    L.d("hcia", "outputImage:" + outputImage.getPath());
                                    outputImage.delete();
                                }
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                uriPho = Uri.fromFile(outputImage);
                                L.d("hcia", "uriPho:" + uriPho);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, uriPho);                                // 指定存储路径，这样就可以保存原图了
                                startActivityForResult(intent, CODEBIG); // 拍照返回图片

                            } catch (IOException e) {
                                e.printStackTrace();
                                L.d("hcia", "e:" + e);
                            }


                        }
                        if (position == 1) {
                            Intent gallaryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(gallaryIntent, SELECT_PHOTO);
                        }


                    }
                })
                .build();

        ee.show();


    }


    public class ImagHelp {
        public int getSrc() {
            return src;
        }

        public void setSrc(int src) {
            this.src = src;
        }

        public Uri getUri() {
            return uri;
        }

        public void setUri(Uri uri) {
            this.uri = uri;
        }

        private int src = R.mipmap.add_img_off;

        public ImagHelp() {
        }

        public ImagHelp(Uri uri) {
            this.uri = uri;
        }

        private Uri uri = null;


    }


}
